<template>
  <div class="equipment-management">
    <!-- 页眉 -->
    <el-row class="page-header">
      <el-col :span="24" class="header-container">
        <div class="page-title">组织机构 - 设施设备</div>
        <div class="user-actions">
          <el-button type="success" icon="plus" @click="handleAddEquipment">添加设备</el-button>
          <el-button @click="handleManagementClick">管理规程</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索框 -->
    <el-col :span="24" class="search-container">
      <el-input
        v-model="searchText"
        placeholder="搜索设备..."
        class="search-input"
        suffix-icon="el-icon-search"
        clearable
      />
    </el-col>

    <!-- 设备表格 -->
    <el-row>
      <el-col :span="24">
        <el-table :data="filteredEquipmentList" border class="custom-table" style="width: 100%">
          <el-table-column
            prop="equipmentId"
            label="设备编号"
            width="120"
            class-name="custom-header"
          />
          <el-table-column prop="equipmentName" label="设备名称" class-name="custom-header" />
          <el-table-column prop="model" label="型号" class-name="custom-header" />
          <el-table-column prop="manufacturer" label="制造商" class-name="custom-header" />
          <el-table-column prop="status" label="状态" width="120" class-name="custom-header">
            <template #default="{ row }">
              <el-tag :type="row.status === '正常' ? 'success' : 'info'">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" class-name="custom-header">
            <template #default="{ row }">
              <div class="button-container">
                <el-button
                  type="text"
                  size="small"
                  icon="view"
                  class="custom-button"
                  @click="handleViewEquipment(row)"
                />
                <el-button
                  type="text"
                  size="small"
                  icon="delete"
                  class="custom-button"
                  @click="handleDeleteConfirmation(row)"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 添加/查看设备弹窗 -->
    <el-dialog
      v-model="addEquipmentDialogVisible"
      :title="isViewMode ? '查看设备' : '添加设备'"
      width="50%"
    >
      <el-form ref="addFormRef" :model="addForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="设备编号"
              :rules="[{ required: true, message: '设备编号不能为空' }]"
            >
              <el-input
                v-model="addForm.equipmentId"
                :disabled="isViewMode"
                placeholder="请输入设备编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号">
              <el-input v-model="addForm.model" :disabled="isViewMode" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称">
              <el-input
                v-model="addForm.equipmentName"
                :disabled="isViewMode"
                placeholder="请输入设备名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购日期">
              <el-date-picker
                v-model="addForm.purchaseDate"
                type="date"
                :disabled="isViewMode"
                placeholder="选择采购日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="制造商">
              <el-input
                v-model="addForm.manufacturer"
                :disabled="isViewMode"
                placeholder="请输入制造商"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用日期">
              <el-date-picker
                v-model="addForm.startDate"
                type="date"
                :disabled="isViewMode"
                placeholder="选择启用日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="addEquipmentDialogVisible = false">关闭</el-button>
        <el-button v-if="!isViewMode" type="primary" @click="handleAddSubmitEquipment">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 管理规程对话框 -->
    <el-dialog v-model="dialogVisible" title="管理规程">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="fileType" label="文件类型" width="120" />
        <el-table-column prop="name" label="名称" width="200" />
        <el-table-column prop="number" label="编号" width="200" />
        <el-table-column prop="addDate" label="添加日期" width="150" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              type="text"
              size="small"
              class="custom-button"
              @click="handleDeleteManagementConfirmation(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="handleAddManagement">新增</el-button>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmitManagement">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增管理规程弹窗 -->
    <el-dialog v-model="innerDialogVisible" title="新增管理规程" width="30%">
      <el-form ref="formRef" :model="form" label-width="80px" :rules="formRules">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="SMP">SMP</el-radio>
            <el-radio label="SOP">SOP</el-radio>
            <el-radio label="SOR">SOR</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="文件" prop="file">
          <el-input v-model="form.file" placeholder="请输入文件名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="innerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmitManagement">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";

// 设备数据和操作
interface Equipment {
  equipmentId: string;
  equipmentName: string;
  model: string;
  manufacturer: string;
  status: string;
  purchaseDate?: string;
  startDate?: string;
}

const equipmentList = ref<Equipment[]>([
  {
    equipmentId: "M0001",
    equipmentName: "机械播种设备",
    model: "T01-042",
    manufacturer: "广东农业设备工厂",
    status: "正常",
  },
  {
    equipmentId: "M0002",
    equipmentName: "离心式撒肥机",
    model: "M-00430B",
    manufacturer: "四川天盛机械科技有限公司",
    status: "正常",
  },
]);

const searchText = ref<string>("");
const addEquipmentDialogVisible = ref<boolean>(false);
const isViewMode = ref<boolean>(false);
const addForm = ref<Equipment>({
  equipmentId: "",
  equipmentName: "",
  model: "",
  manufacturer: "",
  status: "正常",
});

const handleAddEquipment = () => {
  isViewMode.value = false;
  addEquipmentDialogVisible.value = true;
  Object.keys(addForm.value).forEach((key) => (addForm.value[key] = ""));
};

const handleAddSubmitEquipment = () => {
  equipmentList.value.push({ ...addForm.value });
  addEquipmentDialogVisible.value = false;
};

const handleViewEquipment = (row: Equipment) => {
  isViewMode.value = true;
  addEquipmentDialogVisible.value = true;
  Object.assign(addForm.value, row);
};

const handleDeleteConfirmation = (row: Equipment) => {
  ElMessageBox.confirm("确定要删除此设备吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const index = equipmentList.value.indexOf(row);
      if (index !== -1) {
        equipmentList.value.splice(index, 1);
        ElMessage.success("删除成功");
      }
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};

const filteredEquipmentList = computed(() =>
  equipmentList.value.filter(
    (item) =>
      item.equipmentId.includes(searchText.value) || item.equipmentName.includes(searchText.value)
  )
);

// 管理规程数据和操作
const dialogVisible = ref(false);
const innerDialogVisible = ref(false);
const form = reactive({
  type: "",
  name: "",
  number: "",
  file: "",
});
const formRef = ref();
const formRules = {
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  number: [{ required: true, message: "请输入编号", trigger: "blur" }],
  file: [{ required: true, message: "请输入文件名", trigger: "blur" }],
};

const tableData = ref([
  { fileType: "SMP", name: "安全生产规程", number: "001", addDate: "2024-01-01" },
  { fileType: "SOP", name: "设备操作规程", number: "002", addDate: "2024-01-02" },
]);

const handleManagementClick = () => {
  dialogVisible.value = true;
};

const handleAddManagement = () => {
  Object.keys(form).forEach((key) => (form[key] = ""));
  innerDialogVisible.value = true;
};

const handleAddSubmitManagement = () => {
  formRef.value
    ?.validate()
    .then(() => {
      tableData.value.push({ ...form, addDate: new Date().toISOString().split("T")[0] });
      innerDialogVisible.value = false;
      ElMessage.success("新增管理规程成功！");
    })
    .catch((error) => {
      console.error("表单验证失败：", error);
    });
};

const handleDeleteManagementConfirmation = (row: any) => {
  ElMessageBox.confirm("确定要删除此管理规程吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const index = tableData.value.indexOf(row);
      if (index !== -1) {
        tableData.value.splice(index, 1);
        ElMessage.success("删除成功");
      }
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};
</script>
<style scoped>
.equipment-management {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-title {
  font-size: 20px;
  font-weight: bold;
  color: #4caf50;
}
.search-container {
  margin-bottom: 20px;
}
.search-input {
  width: 300px;
}
.el-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}
.custom-button {
  background-color: transparent;
  border: none;
  color: inherit;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
